 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <stdarg.h>
#include "sys_log.h"

int debug_level = MAX_LEVEL;
static int fd;
/*
获取时间字符串
*/
static char* get_time()
{
	static char time_buf[64];
	bzero(time_buf, sizeof(time_buf));

	static time_t t;
	t = time(NULL);

	static struct tm *cur;
	cur = localtime(&t);

	sprintf(time_buf, "%04d-%02d-%02d %02d:%02d:%02d", cur->tm_year + 1900, cur->tm_mon + 1, cur->tm_mday, cur->tm_hour, cur->tm_min, cur->tm_sec);
	return time_buf;
}
/*
以当前的时间做为名字,创建log文件
*/
int log_init()
{

	char path[128];
	time_t t;
	t = time(NULL);  // 获取当前时间
	srand(t);

	struct tm *cur;
	cur = localtime(&t); // 将秒数时间进行结构化处理。

	sprintf(path, "./sys_%04d%02d%02d_%02d%02d%02d_%04ld.log", cur->tm_year + 1900, cur->tm_mon + 1, cur->tm_mday, cur->tm_hour, cur->tm_min, cur->tm_sec, random() % 10000);
	fd = open(path, O_WRONLY | O_CREAT, 0664);
	if (fd < 0) {
		perror("open");
	}
	return fd;
}
/*
日志打印
*/
static char buf[1024]; // 静态数组
static char debug_title[][10] = {"ERROR", "INFO", "DEBUG"};

void log_print(int type, const char *file, const char *func, const int line, const char *format, ...)
{
	bzero(buf, sizeof(buf));
	int i = 0;
	sprintf(buf, "%s [%s] %s:%s():%d ", get_time(), debug_title[type], file, func, line);
	i = strlen(buf);	
	va_list args;	
	va_start(args, format);

	const char *p = format;
	while (*p != '\0') {
		if (*p != '%') {
			buf[i++] = *p;
			p++;
			continue;
		}
		p++;
		switch(*p) {
			case 'c':
				sprintf(buf + i, "%c", (char)va_arg(args, int));
			break;
			case 'd':
				sprintf(buf + i, "%d", va_arg(args, int));
			break;
			case 's':
				sprintf(buf + i, "%s", va_arg(args, char *));
			break;
			case 'p':
				sprintf(buf + i, "%p", va_arg(args, void *));
			break;
			case 'x':
				sprintf(buf + i, "%x", va_arg(args, int));
			break;
			default:
			break;
		}
		i = strlen(buf);
		p++;
	}	
	va_end(args);

	//printf("%s", buf);
	write(fd, buf, strlen(buf));
}

/*
关闭日志文件
*/
void log_destroy(void)
{
	close(fd);
}

